package com.yft.sys.common.exception;

import com.yft.sys.modules.preCheck.controller.base.BaseController;
import org.apache.http.HttpStatus;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理器
 *
 * @author lr
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**=====================系统自定义====================**/

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CommonException.class)
    public Object handleCommonException(CommonException e) {
        logger.error("自定义CommonException:" + e.getMessage(), e);
        return getFailResult(e.getCode(), e.getMsg());
    }

    /**
     * 参数校验错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    public Object handleAuthorizationException(ValidationException e) {
        logger.warn("参数校验异常：" + e.getMessage());
        return getFailResult(e.getCode(), e.getMsg());
    }

    /**=====================系统常用默认返回====================**/

    /**
     * 数据库错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Object handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error("数据库中已存在该记录异常:" + e.getMessage(), e);
        return getFailResult(500, "数据库中已存在该记录");
    }


    /**
     * 无权操作
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(AuthorizationException e) {
        logger.warn("无权访问：", e.getMessage());
        return getFailResult(HttpStatus.SC_UNAUTHORIZED, "没有权限，请联系管理员授权");
    }

    /**
     * 404
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Object noHandlerFoundException(Exception e) {
        logger.warn("404:" + e.getMessage());
        return getFailResult(HttpStatus.SC_NOT_FOUND, "404异常，请求路径未找到,");
    }

    /**
     * 500服务器异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        logger.error("服务器异常:" + e.getMessage(), e);
        return getFailResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, "服务器异常");
    }

}
